

import java.net.*;  // for Socket, ServerSocket, and InetAddress
import java.io.*;   // for IOException and Input/OutputStream
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server extends Thread {

    private static final int BUFSIZE = 4096;   // Size of receive buffer
    private int port;
    private ServerSocket servSock;
    private String dataFromBuffer="";
    int recvMsgSize;   // Size of received message
    byte[] byteBuffer = new byte[BUFSIZE];  // Receive buffer
    Server(int port) throws IOException {
        this.port = port;
        this.servSock = new ServerSocket(port);
        this.servSock.setReuseAddress(true);
    }

    public String passData() {
        return this.dataFromBuffer;
    }

    public void getData() {
        //read the buffer
        //System.out.println(new String(byteBuffer));
        this.dataFromBuffer = new String(byteBuffer);
        //System.out.println(this.dataFromBuffer);
        //clear the buffer
        for (int i=0;i<byteBuffer.length;i++) {
            byteBuffer[i]=0;
        }
        //System.out.println("buffer cleared");
    }
    public void startServer() {
        for (;;) { // Run forever, accepting and servicing connections
            Socket clntSock;
            try {
                clntSock = this.servSock.accept(); // Get client connection


            System.out.println("Handling client at " +
                clntSock.getInetAddress().getHostAddress() + " on port " +
                clntSock.getPort());

            InputStream in = clntSock.getInputStream();
            OutputStream out = clntSock.getOutputStream();

            // Receive until client closes connection, indicated by -1 return
            while ((recvMsgSize = in.read(byteBuffer)) != -1) {
                //out.write(byteBuffer, 0, recvMsgSize);
                //System.out.println(new String(byteBuffer));
                this.getData();
            }



            this.getData();
            clntSock.close();  // Close the socket.  We are done with this client!
            }
            catch (Exception ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void run() {
        //try {
            this.startServer();
        //} catch (IOException ex) {
         //   Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        //}
  }
   /*
  public static void main(String[] args) throws IOException {
       Server tcpServer = new Server(5441);
       tcpServer.startServer();
  }
  */
}